const { questionCategories } = require('../../utils/questions.js');
const StudyManager = require('../../utils/studyManager.js');

Page({
  data: {
    // 题库数据
    questionCategories: questionCategories,
    
    // 练习相关数据
    isStarted: false, // 是否开始练习
    currentQuestion: null, // 当前题目
    currentIndex: 0, // 当前题目索引
    totalQuestions: 0, // 总题目数
    questionList: [], // 题目列表
    showAnswer: false, // 是否显示答案
    correctCount: 0, // 答对题目数
    wrongCount: 0, // 答错题目数
    progressPercent: 0, // 进度百分比
    
    // 练习设置
    practiceMode: 'random', // 练习模式：random-随机，sequential-顺序
    categoryFilter: 'all', // 分类筛选：all-全部，或具体分类id
    topicFilter: 'all', // 专题筛选：all-全部，或具体专题id
    
    // 统计数据
    practiceStats: {
      totalPracticed: 0,
      totalCorrect: 0,
      totalWrong: 0,
      accuracy: 0
    }
  },

  onLoad(options) {
    // 加载练习统计数据
    this.loadPracticeStats();
    
    // 处理从其他页面跳转过来的参数
    if (options.type === 'favorites') {
      this.loadFavoritesQuestions();
    } else if (options.questionId) {
      this.loadSingleQuestion(options.questionId);
    }
  },

  // 加载收藏题目
  loadFavoritesQuestions() {
    const favorites = wx.getStorageSync('favorites') || [];
    if (favorites.length === 0) {
      wx.showToast({
        title: '暂无收藏题目',
        icon: 'none'
      });
      return;
    }
    
    // 将收藏的题目转换为练习格式
    const questionList = favorites.map(fav => ({
      id: fav.id,
      title: fav.title,
      answer: this.getQuestionAnswer(fav.id),
      categoryId: fav.category,
      categoryName: this.getCategoryName(fav.category),
      topicId: 'favorites',
      topicName: '收藏题目'
    }));
    
    this.setData({
      categoryFilter: 'favorites',
      topicFilter: 'favorites'
    });
    
    this.startPracticeWithQuestions(questionList);
  },

  // 加载单个题目
  loadSingleQuestion(questionId) {
    const question = this.findQuestionById(questionId);
    if (question) {
      this.startPracticeWithQuestions([question]);
    }
  },

  // 根据ID查找题目
  findQuestionById(questionId) {
    for (const category of questionCategories) {
      for (const topic of category.topics) {
        for (const question of topic.questions) {
          if (question.id == questionId) {
            return {
              id: question.id,
              title: question.title,
              answer: question.answer,
              categoryId: category.id,
              categoryName: category.name,
              topicId: topic.id,
              topicName: topic.name
            };
          }
        }
      }
    }
    return null;
  },

  // 获取题目答案
  getQuestionAnswer(questionId) {
    const question = this.findQuestionById(questionId);
    return question ? question.answer : '';
  },

  // 获取分类名称
  getCategoryName(categoryId) {
    const category = questionCategories.find(cat => cat.id === categoryId);
    return category ? category.name : '未知分类';
  },

  // 使用指定题目列表开始练习
  startPracticeWithQuestions(questionList) {
    if (questionList.length === 0) {
      wx.showToast({
        title: '暂无题目可练习',
        icon: 'none'
      });
      return;
    }

    this.setData({
      isStarted: true,
      questionList: questionList,
      totalQuestions: questionList.length,
      currentIndex: 0,
      currentQuestion: questionList[0],
      showAnswer: false,
      correctCount: 0,
      wrongCount: 0,
      progressPercent: questionList.length > 0 ? Math.round((1 / questionList.length) * 100) : 0
    });
  },

  // 开始练习
  startPractice() {
    // 生成题目列表
    const questionList = this.generateQuestionList();
    
    if (questionList.length === 0) {
      wx.showToast({
        title: '暂无题目可练习',
        icon: 'none'
      });
      return;
    }

    this.setData({
      isStarted: true,
      questionList: questionList,
      totalQuestions: questionList.length,
      currentIndex: 0,
      currentQuestion: questionList[0],
      showAnswer: false,
      correctCount: 0,
      wrongCount: 0,
      progressPercent: questionList.length > 0 ? Math.round((1 / questionList.length) * 100) : 0
    });
  },

  // 生成题目列表
  generateQuestionList() {
    let allQuestions = [];
    
    // 根据筛选条件获取题目
    questionCategories.forEach(category => {
      if (this.data.categoryFilter === 'all' || category.id === this.data.categoryFilter) {
        category.topics.forEach(topic => {
          if (this.data.topicFilter === 'all' || topic.id === this.data.topicFilter) {
            topic.questions.forEach(question => {
              allQuestions.push({
                id: question.id,
                title: question.title,
                answer: question.answer,
                categoryId: category.id,
                categoryName: category.name,
                topicId: topic.id,
                topicName: topic.name
              });
            });
          }
        });
      }
    });

    // 随机打乱题目顺序
    if (this.data.practiceMode === 'random') {
      for (let i = allQuestions.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [allQuestions[i], allQuestions[j]] = [allQuestions[j], allQuestions[i]];
      }
    }

    return allQuestions;
  },

  // 显示答案
  showAnswer() {
    this.setData({
      showAnswer: true
    });
  },

  // 隐藏答案
  hideAnswer() {
    this.setData({
      showAnswer: false
    });
  },

  // 标记为正确
  markCorrect() {
    const currentQuestion = this.data.currentQuestion;
    
    // 记录学习数据
    StudyManager.recordStudy(
      currentQuestion.id,
      true,
      currentQuestion.categoryName,
      currentQuestion.title
    );
    
    this.setData({
      correctCount: this.data.correctCount + 1
    });
    this.nextQuestion();
  },

  // 标记为错误
  markWrong() {
    const currentQuestion = this.data.currentQuestion;
    
    // 记录学习数据
    StudyManager.recordStudy(
      currentQuestion.id,
      false,
      currentQuestion.categoryName,
      currentQuestion.title
    );
    
    this.setData({
      wrongCount: this.data.wrongCount + 1
    });
    this.nextQuestion();
  },

  // 下一题
  nextQuestion() {
    const nextIndex = this.data.currentIndex + 1;
    
    if (nextIndex >= this.data.totalQuestions) {
      // 练习完成
      this.finishPractice();
      return;
    }
    this.setData({
      currentIndex: nextIndex,
      currentQuestion: this.data.questionList[nextIndex],
      showAnswer: false,
      progressPercent: Math.round(((nextIndex + 1) / this.data.totalQuestions) * 100)
    });
  },

  // 上一题
  prevQuestion() {
    if (this.data.currentIndex <= 0) {
      return; // 如果是第一题，不执行任何操作
    }
    const prevIndex = this.data.currentIndex - 1;
    this.setData({
      currentIndex: prevIndex,
      currentQuestion: this.data.questionList[prevIndex],
      showAnswer: false,
      progressPercent: Math.round(((prevIndex + 1) / this.data.totalQuestions) * 100)
    });
  },

  // 完成练习
  finishPractice() {
    const accuracy = this.data.totalQuestions > 0 ? 
      Math.round((this.data.correctCount / this.data.totalQuestions) * 100) : 0;
    
    // 更新统计数据
    this.updatePracticeStats(this.data.totalQuestions, this.data.correctCount, this.data.wrongCount);
    
    wx.showModal({
      title: '练习完成',
      content: `本次练习完成！\n总题数：${this.data.totalQuestions}\n答对：${this.data.correctCount}\n答错：${this.data.wrongCount}\n正确率：${accuracy}%`,
      showCancel: false,
      confirmText: '确定',
      success: () => {
        this.setData({
          isStarted: false,
          currentQuestion: null,
          showAnswer: false
        });
      }
    });
  },

  // 结束练习
  endPractice() {
    wx.showModal({
      title: '确认结束',
      content: '确定要结束当前练习吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            isStarted: false,
            currentQuestion: null,
            showAnswer: false
          });
        }
      }
    });
  },

  // 切换练习模式
  switchMode(e) {
    const mode = e.currentTarget.dataset.mode;
    this.setData({
      practiceMode: mode
    });
  },

  // 选择分类
  selectCategory(e) {
    const categoryId = e.currentTarget.dataset.id;
    this.setData({
      categoryFilter: categoryId,
      topicFilter: 'all'
    });
  },

  // 选择专题
  selectTopic(e) {
    const topicId = e.currentTarget.dataset.id;
    this.setData({
      topicFilter: topicId
    });
  },

  // 加载练习统计数据
  loadPracticeStats() {
    const stats = wx.getStorageSync('practiceStats') || {
      totalPracticed: 0,
      totalCorrect: 0,
      totalWrong: 0,
      accuracy: 0
    };
    
    this.setData({
      practiceStats: stats
    });
  },

  // 更新练习统计数据
  updatePracticeStats(total, correct, wrong) {
    const stats = this.data.practiceStats;
    stats.totalPracticed += total;
    stats.totalCorrect += correct;
    stats.totalWrong += wrong;
    stats.accuracy = stats.totalPracticed > 0 ? 
      Math.round((stats.totalCorrect / stats.totalPracticed) * 100) : 0;
    
    this.setData({
      practiceStats: stats
    });
    
    wx.setStorageSync('practiceStats', stats);
  }
}); 